/**
 * 
 */
package com.lanswon.qzsmk.task.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.AppContants;
import com.lanswon.qzsmk.base.BlackListContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.BlackListGenMapper;
import com.lanswon.qzsmk.dao.BlackListRcMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.PhotoMapper;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.AppOpenReg;
import com.lanswon.qzsmk.model.BlackListGen;
import com.lanswon.qzsmk.model.BlackListRc;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.Photo;
import com.lanswon.qzsmk.task.TaskList;
import com.lanswon.qzsmk.util.FileUtil;
import com.lanswon.qzsmk.util.FtpUtil;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.vo.UploadFtpVo;

/**
 * 定时任务实现类
 * 
 * @author sun
 *
 */
@Component
public class TaskListImpl implements TaskList {

	private static final Integer UNBIND_DAYS = 7;

	@Autowired
	CardControlMapper ccm;

	@Autowired
	CardDataMapper cdm;

	@Autowired
	BlackListGenMapper blgm;

	@Autowired
	BlackListRcMapper blrm;

	@Autowired
	PhotoMapper photoMapper;
	
	@Autowired
	CertMapper certMapper;
	
	@Autowired
	AppOpenRegMapper appOpenRegMapper;
	
	private static Logger logger = (Logger) LoggerFactory.getLogger(TaskListImpl.class);

	
	@Scheduled(cron = "0 0 23 * * ?") //每晚24点检查一遍
	@Override
	public void autoUnbindTask() {// 自动解挂时间7天， 7天后如果不主动解挂，程序自动解挂  卡状态更改正常、黑名单失效、个人子账户正常
		String cardStatus = CardContants.CARD_STATE_ORAL_LOSS;
		List<CardControl> lc = ccm.queryOralLossList(cardStatus);
		for (CardControl cc : lc) {
			Date oralLossDate = cc.getLastDate();
			long ms = UNBIND_DAYS * 24 * 3600 * 1000;
			long oralLossDatems = oralLossDate.getTime();
			Date now = new Date();
			
			if ((ms + oralLossDatems) < System.currentTimeMillis()) {
				cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
				cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);// 黑名单标识
				cc.setLastDate(new Date());
				cc.setLastOperator("系统");
				cc.setLossDate(null);
				cc.setLossReason(null);
				cc.setIsRead(CardContants.CARD_IS_READ);
				cc.setRemark("口头挂失已超过" + UNBIND_DAYS + "天,程序自动帮你解挂");
				ccm.updateCardControl(cc);

				CardData cd = cdm.queryCardDataById(cc.getCardDataId());

				BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(cd
						.getCitizenCardNo());
				bb.setBlReCount(bb.getBlReCount() + 1);// 解除黑名单次数
				bb.setBlReReason(BlackListContants.BL_RE_REASON_AUTOMATIC_HANG_UP);// 解除黑名单原因
				bb.setRelieveDate(now);// 解除日期
				bb.setAvailDate(null);// 生效日期
				bb.setBlackMode(null);
				bb.setCurStatus(BlackListContants.BL_CUR_STATUS_Relieve);// 当前状态
				bb.setLastBlRcDate(now);// 最后更新日期
				blgm.update(bb);

				BlackListRc blr = new BlackListRc();
				blr.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
				// blr.setAvailDate(null);// 生效日期
				blr.setRelieveDate(now);// 解除日期
				// blr.setBlackMode(null);// 置黑方式 0-系统;
				// blr.setBlReason(null);// 进黑名单原因
				blr.setBlReReason(BlackListContants.BL_RE_REASON_AUTOMATIC_HANG_UP);// 解除黑名单原因
				blr.setRemark("解挂记录--系统自动解挂(口头挂失)");
				blr.setOperDate(now);
				blrm.insert(blr);

			}

		}
		// 下面是测试啊 funk u!!!!
		// DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// System.out.println(sdf.format(new Date())+"*********任务每2秒执行一次进入测试");

	}

	
	@Override
	@Scheduled(cron = "0 0 20 * * ?") //每晚20点检查一遍
	public void uploadToFTP() {
		logger.debug("****************开始清理数据*******************");
		List<UploadFtpVo> list = new ArrayList<>();
		logger.debug("1");
		List<Photo> ls = new ArrayList<>(); //图片
		List<File> fList = new ArrayList<>();
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();
		String root = servletContext.getRealPath("/");
		File f = new File(root + PathContants.PROJECT_PATH_EXCEL_IMPORTED);
		File f1 = new File(root + PathContants.PROJECT_PATH_IMG_IMPORTED);
		File[] files = f.listFiles();
		File[] files1 = f1.listFiles();
		logger.debug("正在搜索excel....");
		if(files != null && files.length > 0){
			fList.add(f);
			Map<String,InputStream> map = new HashMap<>();
			
			UploadFtpVo vo =new UploadFtpVo(PathContants.FTP_PATH_EXCEL);
			for(File file:files){
				InputStream input;
				try {
					input = new FileInputStream(file);
					map.put(file.getName(),input);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					logger.debug("文件【{}】转输入流失败",file.getName());
					String msg="系统找不到文件";
					logger.error(msg);
					throw new SystemException(SystemException.FileNotFoundException, msg);

				}
				
			}
			vo.setMap(map);
			list.add(vo);
		}else{
			logger.debug("未搜索到excel....");
		}
		logger.debug("正在搜索photo....");
		if(files1 != null && files1.length > 0){
			//
			for(File file:files1){
				String applyNo = file.getName();//批次文件夹
				fList.add(file);
				Map<String,InputStream> map1 = new HashMap<>();
				UploadFtpVo vo =new UploadFtpVo(PathContants.FTP_PATH_PHOTO);			
				File[] fff = file.listFiles();//照片
				for(File fi:fff){
					String name = fi.getName();
					Photo p = new Photo();
					p.setPaperNo(name.substring(0,name.indexOf(".")));
					p.setPhoto(vo.getPath());
					ls.add(p);
					InputStream input;
					try {
						input = new FileInputStream(fi);
						map1.put(name,input);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
						logger.error("文件【{}】转输入流失败",fi.getName());
						String msg="系统找不到文件";
						throw new SystemException(SystemException.FileNotFoundException, msg);

					}
					vo.setMap(map1);
				}
				list.add(vo);
			}
		}else{
			logger.debug("未搜索到photo....");
		}
		
		logger.debug("准备上传至ftp....");
		//上传
		try {
			FtpUtil.uploadFile_ftp(PathContants.FTP_URL, PathContants.FTP_PORT,
					PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, list);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("上传文件到FTP失败");
			String msg="IO流异常";
			throw new SystemException(SystemException.IOException, msg);

		}
		
		//清除源文件
		logger.debug("正在删除源文件...");
		for(File fg:fList){
			FileUtil.delDir(fg);
		}
		
		
		//更新图片路径
		logger.debug("正在更新照片路径...");
		if(ls.size()>0)
			photoMapper.updateBatch(ls);
		
		logger.debug("****************清理数据完毕*******************");

		
		
		
	}
	
	@Scheduled(cron = "0 0 23 * * ?") //每晚23点初始化序列号
	public void updateSeq(){
		SequenceNumberUtil.setCertSeq(0);
		SequenceNumberUtil.setBusSeq(0);
	}


	@Override
	@Scheduled(cron = "0 0 22 * * ?") //每晚22点执行
	public void bikeAppToBus() {
		logger.debug("即将生成文件，当日开通自行车应用的卡号");
		Date now= new Date();
		List<AppOpenReg> list = appOpenRegMapper.queryDayOpenApp(now, AppContants.APP_FLAG_BIKE);
		if(list.size()==0){
			return;
		}
		StringBuffer sb = new StringBuffer();
		for(int i = 0;i<list.size();i++){
			AppOpenReg s = list.get(i);
			int index = i+1;
			sb.append(index+"|"+s.getCitizenCardNo());
			sb.append("\r\n");
		}
		
		String content = FileUtil.cardTitle(FileUtil.str3)+sb.toString();
		byte[] b = null;
		try {
			b = content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			String msg1="转码异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		}
		String filePath = PathContants.FTP_PATH_OPENBIKEAPP;
		String filename = DateFormatUtils.format(now, "yyyyMMdd")+".txt";
		InputStream in = new  ByteArrayInputStream(b);  
		FtpUtil.uploadFile(PathContants.FTP_URL, PathContants.FTP_PORT, PathContants.FTP_USERNAME, PathContants.FTP_PASSWORD, filePath, filename, in);
		logger.info("FTP路径[{}],文件名[{}],上传成功",filePath,filename);
		
	}

}
